package com.taxi.driver.module.recruit.selectcar;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.taxi.driver.R;
import com.taxi.driver.data.entity.CarModleEntity;

import java.util.List;

/**
 * Created by Curry on 2018/5/17.
 */

public class CarListAdapter  extends BaseAdapter implements SectionIndexer
{
    private List<CarModleEntity> mEntities;
    private Context mContext;
    public CarListAdapter(List<CarModleEntity> entities, Context context) {
        mEntities = entities;
        mContext = context;
    }

    @Override
    public int getCount()
    {
        return mEntities.size();
    }

    @Override
    public Object getItem(int position)
    {
        return mEntities.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent)
    {

        ViewHolder viewHolder = null;
        CarModleEntity sortEntity = mEntities.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.car_modle_item, null);
            viewHolder.mTvLetter = (TextView) view.findViewById(R.id.tv_item_letter);
            viewHolder.mTvTitle = (TextView) view.findViewById(R.id.tv_item_title);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        int section = getSectionForPosition(position);
        if (position == getPositionForSection(section)) {
            viewHolder.mTvLetter.setVisibility(View.VISIBLE);
            viewHolder.mTvLetter.setText(sortEntity.getSortLetters());
        } else {
            viewHolder.mTvLetter.setVisibility(View.GONE);
        }
        viewHolder.mTvTitle.setText(sortEntity.getName());
        return view;
    }

    @Override
    public Object[] getSections()
    {
        return  null;
    }

    @Override
    public int getPositionForSection(int sectionIndex)
    {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = mEntities.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == sectionIndex) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getSectionForPosition(int position)
    {
        return mEntities.get(position).getSortLetters().charAt(0);
    }
    private class ViewHolder {
        TextView mTvTitle;
        TextView mTvLetter;
    }
}
